package cn.ratel.route;

import cn.ratel.component.Handlers;
import com.google.common.base.Preconditions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HandlerContext {
	private HttpServletRequest request;
	private HttpServletResponse response;
	private String uri;
	private int index = 0;
	private String controllerName = "index";
	private String actionName = "index";

	HandlerContext(HttpServletRequest request, HttpServletResponse response, String uri) {
		this.request = request;
		this.response = response;
		this.uri = uri;

		Preconditions.checkNotNull(uri);

		uri = uri.startsWith("/") ? uri.substring(1) : uri;
		uri = uri.endsWith("/") ? uri.substring(0, uri.length() - 1) : uri;

		if ("".equals(uri)) {
			return;
		}
		String[] route = uri.split("/");
		if (route.length >= 2) {
			controllerName = route[0];
			actionName = route[1];
		} else if (route.length == 1) {
			controllerName = route[0];
		}
	}

	public void next() {
		Handlers.me().getHandlers().get(++index).handle(this);
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public String getUri() {
		return uri;
	}

	public String getControllerName() {
		return controllerName;
	}

	public String getActionName() {
		return actionName;
	}
}
